<?php
declare (strict_types = 1);

namespace app\command\logic;

use app\api\services\MemberService;
use app\api\services\SandService;
use app\command\Carefree;
use app\command\logic\BaseLogic;
use app\common\models\Carefree\CarefreeOrder;
use app\common\models\Carefree\CarefreeRedAmountLog;
use app\common\models\Community\CommunityUser;
use app\common\models\Member\Member;
use app\common\models\Member\MemberAgency;
use app\common\models\Member\MemberAmountLog;
use app\common\models\Member\MemberRechargeOrder;
use app\common\models\Member\MemberWithdraw;
use think\console\Output;
use think\facade\Log;

/**
 * 统计-订单交易数据
 * php think cli stats_person_member_data --msg='{"days":30}'
 */
class CliStatsPersonMemberLogic extends BaseLogic implements CliInterface
{

    /**
     * 入口方法
     * {@inheritdoc}
     */
    public function run(Output $output, array $msg): bool
    {
        if(isset($msg['date']) && $msg['date'] == 'today'){
            $this->dataForData(date('Y-m-d 23:59:59'));
        }else{
            $this->dataForData(date('Y-m-d 23:59:59',strtotime('-1 day')));
        }
        return true;
    }

    private static function dataForData($date): void
    {
        $list = Member::getInstance()->where('deleted',0)->select();
        //$start = date('Y-m-d 23:59:59',strtotime('-1 day'));
        $start = $date;
        foreach($list as $v){
            $m = MemberService::getInstance()->account($v['id']);
            if(empty($m) || $m['isActiveSd'] == 0){
                continue;
            }
            try{
                $where = [
                    ['user_id','=',$v['id']],
                ];
                $account = \think\facade\Db::table('member_account')->where($where)->find();
                $ret = SandService::getInstance()->accountBalanceQuery($v['id']);
                $sand_money = 0;
                if(isset($ret['resultStatus']) && $ret['resultStatus'] == 'success'){
                    $sand_money = !empty($ret['accountList'][0]['availableBal']) ? $ret['accountList'][0]['availableBal'] : 0;
                    /*if(!empty($ret['accountList'][0]['frozenBal'])){
                        $sand_money = bcadd((string)$ret['accountList'][0]['availableBal'],(string)$sand_money,2);
                    }*/
                }
                $finance = MemberService::getInstance()->finance($v['id']);
                $where = [
                    ['user_id','=',$v['id']],
                    ['status','=',1],
                ];
                $recharge_total_balance = MemberRechargeOrder::getInstance()->where($where)->sum('money');
                $where = [
                    ['user_id','=',$v['id']],
                    ['trans_name','=','银行卡充值'],
                    ['trans_time','<=',$start]
                ];
                $recharge_total_sand = \think\facade\Db::table('stats_sand_member_data')->where($where)->sum('act_amt') ?: 0;
                $where = [
                    ['user_id','=',$v['id']],
                    ['status','in',[0,1]],
                    ['type','=',2],
                    ['create_at','<=',$start]
                ];
                $amount_to_alipay = MemberWithdraw::getInstance()->where($where)->sum('amount') ?: '0.00';
                $where = [
                    ['user_id','=',$v['id']],
                    ['trans_name','=','提现'],
                    ['trans_time','<=',$start]
                ];
                $sand_to_card = \think\facade\Db::table('stats_sand_member_data')->where($where)->sum('act_amt') ?: "0.00";

                //余额提现到电子钱包
                $where = [
                    ['user_id','=',$v['id']],
                    ['status','in',[0,1]],
                    ['type','=',3],
                    ['create_at','<=',$start]
                ];
                $amount_to_sand = MemberWithdraw::getInstance()->where($where)->sum('amount') ?: '0.00';
                $tx_total = bcadd((string)$amount_to_alipay,(string)$amount_to_sand,2);
                $green = $finance['communityAmount']+$finance['inviteAmount']+$finance['giftBagAmount'];
                $where = [
                    ['user_id','=',$v['id']],
                    ['pay_status','=',2],
                    ['status','=',1],
                    ['is_refund','=',0],
                    ['order_status','in',[1,4]],
                ];
                $alipay = \think\facade\Db::table('order_pay')->where($where)->sum('pay_price') ?: "0.00";
                $community_money = CommunityUser::getInstance()->where('user_id',$v['id'])->sum('total_amount') ?: '0.00';
                //1待发货 2待收货 3已收货 4已完成
                $carefree_money = CarefreeOrder::getInstance()->where('user_id',$v['id'])->where('status','in',[1,2,3,4])->sum('sell_price') ?: '0.00';
                //订单汇总 = 社区金额+无忧订单金额
                $order_total = bcadd((string)$community_money,(string)$carefree_money,2);
                //总合计：收入（电子钱包充值+余额总充值+支付宝支付）-支付（电子钱包提现到银行卡+提现到支付宝+电子钱包余额+个人余额+绿色积分）
                $total = ($recharge_total_sand + $recharge_total_balance + $alipay) - ($sand_to_card + $amount_to_alipay + $sand_money + $finance['amount'] + $green);
                //社区转无忧的订单金额
                $community_to_carefree = CarefreeOrder::getInstance()->where('user_id',$v['id'])->where('status','in',[1,2,3,4])->sum('deduction') ?: '0.00';

                $carefree_sent = CarefreeRedAmountLog::getInstance()->where('user_id',$v['id'])->where('status',1)->sum('amount') ?: '0.00';
                $carefree_no_sent = bcsub((string)$carefree_money,(string)$carefree_sent,2);
                $data = [
                    'user_id' => $v['id'],
                    'real_name' => $account['real_name'] ?? '',
                    'phone' => $v['phone'],
                    'sand_money' => $sand_money,
                    'balance' => $finance['amount'],
                    'green' => bcadd((string)$green, "0",2),
                    'recharge_total_sand' => $recharge_total_sand,
                    'recharge_total_balance' => $recharge_total_balance,
                    'tx_total' => $tx_total,
                    'alipay' => $alipay,
                    'community_money' => $community_money,
                    'carefree_money' => $carefree_money,
                    'order_total' => $order_total,
                    'total' => bcadd((string)$total,"0",2),
                    'amount_to_alipay' => $amount_to_alipay,
                    'amount_to_sand' => $amount_to_sand,
                    'sand_to_card' => $sand_to_card,
                    'community_to_carefree' => $community_to_carefree,
                    'carefree_sent' => $carefree_sent,
                    'carefree_no_sent' => $carefree_no_sent,
                ];
                $where = [
                    ['user_id','=',$v['id']]
                ];
                $ret = \think\facade\Db::table('stats_person_member_data')->where($where)->find();
                if($ret){
                    $data['update_at'] = date('Y-m-d H:i:s');
                    \think\facade\Db::table('stats_person_member_data')->where($where)->update($data);
                }else{
                    \think\facade\Db::table('stats_person_member_data')->insert($data);
                }
            }catch (\Exception $ex){
                Log::error($ex->getMessage().$ex->getLine());
                echo $ex->getMessage().$ex->getLine();
            }

        }

    }
}
